package com.sgu6.sgu6_machine.ui;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.Process;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.danikula.videocache.HttpProxyCacheServer;
import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.enums.MachineStatusEnum;
import com.sgu6.middleware.event.DataRefreshEvent;
import com.sgu6.middleware.event.MachineCmdEvent;
import com.sgu6.middleware.event.MachineIdEvent;
import com.sgu6.middleware.event.MachineStatusEvent;
import com.sgu6.middleware.event.MakeRiceEvent;
import com.sgu6.middleware.event.MakeWaterEvent;
import com.sgu6.middleware.event.UpdateDomainEvent;
import com.sgu6.middleware.event.WarningEvent;
import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.middleware.util.AppUtils;
import com.sgu6.middleware.util.DateUtils;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.netty.NettyClient;
import com.sgu6.netty.container.Machine;
import com.sgu6.netty.dto.AppAdDto;
import com.sgu6.netty.dto.AppVersionDto;
import com.sgu6.netty.utils.NettyHelper;
import com.sgu6.redis.cache.MachineCache;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseA;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.config.MachineConfig;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.db.DBManager;
import com.sgu6.sgu6_machine.dto.ApiErrorDto;
import com.sgu6.sgu6_machine.dto.ChargeDto;
import com.sgu6.sgu6_machine.dto.ElectricityParams;
import com.sgu6.sgu6_machine.dto.EletricDto;
import com.sgu6.sgu6_machine.dto.PowerDto;
import com.sgu6.sgu6_machine.dto.SysNoticeDto;
import com.sgu6.sgu6_machine.dto.VoltageDto;
import com.sgu6.sgu6_machine.event.FinishOrderEvent;
import com.sgu6.sgu6_machine.event.MachineReadyEvent;
import com.sgu6.sgu6_machine.event.NetChangeEvent;
import com.sgu6.sgu6_machine.event.PowerSaveEvent;
import com.sgu6.sgu6_machine.event.SelectTypeEvent;
import com.sgu6.sgu6_machine.event.SignalStrengthsEvent;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.service.ComS;
import com.sgu6.sgu6_machine.service.InitIntentS;
import com.sgu6.sgu6_machine.service.LocationS;
import com.sgu6.sgu6_machine.ui.activity.LoginA;
import com.sgu6.sgu6_machine.ui.dialog.UpdateDialogF;
import com.sgu6.sgu6_machine.ui.fragment.BuyF;
import com.sgu6.sgu6_machine.ui.fragment.MillF;
import com.sgu6.sgu6_machine.ui.fragment.SelectF;
import com.sgu6.sgu6_machine.ui.fragment.WaterF;
import com.sgu6.sgu6_machine.ui.views.SignalView;
import com.sgu6.sgu6_machine.util.FileUtils;
import com.sgu6.sgu6_machine.util.ImageDownloadUtil;
import com.sgu6.sgu6_machine.util.OssUtil;
import com.sgu6.sgu6_machine.util.ToastUtil;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;

public class MainA extends BaseA implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, View.OnTouchListener {

    @BindView(R.id.videoContainer)
    LinearLayout videoContainer;
    @BindView(R.id.videoView)
    VideoView videoView;
    @BindView(R.id.tv_machine_status)
    TextView tvMachineStatus;
    @BindView(R.id.tv_machine_no)
    TextView tvMachineNo;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.home)
    LinearLayout home;
    @BindView(R.id.signalView)
    SignalView signalView;
    @BindView(R.id.fragment_container)
    FrameLayout fl;
    @BindView(R.id.ll_header)
    LinearLayout llHeader;
    @BindView(R.id.btn_buy)
    TextView btnBuy;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.view_app_bottom)
    View appBottom;
    @BindView(R.id.view_setting)
    View viewSetting;
    @BindView(R.id.iv_code)
    ImageView ivCode;
    @BindView(R.id.tv_service)
    TextView tvService;


    public CountDownTimer touchTimer, finishOrderTimer;
    public boolean isTimerRunning = false;
    public int curSecond = 0;
    public int totalSecond = 60;
    public int curAdPosition = 0; //当前播放的是第几个广告
    public List<String> videoUrls = new ArrayList<>(); //视频集合
    private HttpProxyCacheServer proxy; //视频缓存代理
    private MachineP machineP = new MachineP();


    Fragment selectF, buyF, millF, waterF;
    FragmentManager fm;
    FragmentTransaction ft;

    Timer heartTimer, updateTimer, powerTimer;
    TimerTask heartTask;


    DialogFragment updateF, upgradeNoticeF;

    private ComS comS;
    private boolean uploadWarn = false;
    private Intent locationServiceI, phoneSignalStateServiceI;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            ComS.MachineBinder myBinder = (ComS.MachineBinder) binder;
            comS = myBinder.getService();
            Log.i(TAG, "onServiceConnected: ");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected: ");
        }
    };

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState); 空实现解决异常重启后，Fragment重叠问题
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFullScreen();

        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);

        loadLocalData();

        startService();

        startService(new Intent(this, InitIntentS.class));

//        loadMachineCache();
//        showWarning("机器离线");

        startPowerTimer();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMachineReadyEvent(MachineReadyEvent event) {

    }


    public void loadLocalData() {
        try {
            MachineContainer.machineConfigDto.appVersion = AppUtils.getVersionInfo(this);
            initUI();
            machineConfig.updateMachineConfig(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadData() {
        ThreadManager.getThreadPollProxy().execute(() -> {
            try {
                Thread.sleep(5000);
                loadMachineCache();
                MachineContainer.machineConfigDto.appVersion = AppUtils.getVersionInfo(this);
                NettyClient.INSTANCE.connect(MachineContainer.machineConfigDto.machineNo, MachineContainer.machineConfigDto.appVersion, MachineContainer.machineConfigDto.isBeta ? MachineContainer.machineConfigDto.socketUrl : Constant.SOCKET_HOST_DEV, MachineContainer.machineConfigDto.isBeta ? Constant.SOCKET_PORT_BETA : Constant.SOCKET_PORT_DEV);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    private void startService() {
        bindService(new Intent(MainA.this, ComS.class), conn, Context.BIND_AUTO_CREATE);
//        locationServiceI = new Intent(this, PhoneSignalStateS.class);
        phoneSignalStateServiceI = new Intent(this, LocationS.class);
//        startService(locationServiceI);
        startService(phoneSignalStateServiceI);
    }

    private void loadMachineCache() {
        MachineContainer.machineInfo = MachineCache.getMachineInfo(MachineContainer.machineConfigDto.isBeta ? MachineContainer.machineConfigDto.adminApiDomain : Constant.ADMIN_API_DOMAIN_DEV, MachineContainer.machineConfigDto.machineNo);
        if (MachineContainer.machineInfo != null && MachineContainer.machineInfo.getMerchantId() != null) {
            MachineContainer.machineConfigDto.merchantId = MachineContainer.machineInfo.getMerchantId();
            MachineContainer.machineConfigDto.appVersion = AppUtils.getVersionInfo(this);
            runOnUiThread(() -> {
                initLogo();
                initAD();
                initBottomColor();
            });
            try {
                machineConfig.updateMachineConfig(MainA.this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    public void initTimer() {
        heartTimer = new Timer();
        updateTimer = new Timer();
        powerTimer = new Timer();
    }


    public void startMachineHeartTimer() {
        heartTask = new TimerTask() {
            @Override
            public void run() {
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.心跳包.code()));
            }
        };
        heartTimer.schedule(heartTask, 500, Constant.socketHeartbeatTime * 1000);
    }

    public void stopMachineHeartTimer() {
        if (heartTask != null) {
            heartTask.cancel();
            heartTask = null;
        }
    }

    public void startFinishOrderTimer() {
        finishOrderTimer.start();
    }

    public void stopFinishOrderTimer() {
        finishOrderTimer.cancel();
    }


    @SuppressLint({"CommitTransaction", "ClickableViewAccessibility"})
    @Override
    public void initUI() {

        initMachineNo(); //显示机器号

        initCountDownTimer();

        initTimer();

        hideFooter();

        initFragments();

        tvMachineStatus.setSelected(true);

        if (!MachineContainer.machineConfigDto.netSignal) {
            signalView.setVisibility(View.GONE);
        }

        home.setOnTouchListener(this);

        initLogo();

        initAD();

    }

    private void initBottomColor() {
        if (MachineContainer.machineInfo != null) {
            if (MachineContainer.machineInfo.getColour() == null || MachineContainer.machineInfo.getColour().equals("")) {
                appBottom.setBackgroundColor(getResources().getColor(R.color.themeColor));
                tvBack.setTextColor(getResources().getColor(R.color.themeColor));
            } else {
                appBottom.setBackgroundColor(Color.parseColor(MachineContainer.machineInfo.getColour()));
                tvBack.setTextColor(Color.parseColor(MachineContainer.machineInfo.getColour()));
            }
        } else {
            appBottom.setBackgroundColor(Color.parseColor(MachineContainer.machineConfigDto.themeColor));
            tvBack.setTextColor(Color.parseColor(MachineContainer.machineConfigDto.themeColor));
        }
    }


    private void initFragments() {
        buyF = BuyF.newInstance("");
        millF = MillF.newInstance("");
        selectF = SelectF.newInstance("");
        waterF = WaterF.newInstance("");


        fm = getSupportFragmentManager();
        ft = fm.beginTransaction();
        ft.add(R.id.fragment_container, selectF, "select");
        ft.add(R.id.fragment_container, buyF, "buy");
        ft.add(R.id.fragment_container, millF, "mill");
        ft.add(R.id.fragment_container, waterF, "water");

        ft.hide(buyF);
        ft.hide(millF);
        ft.hide(waterF);
        ft.commitAllowingStateLoss();
    }


    public void initMachineNo() {
        tvMachineNo.setText(MachineContainer.machineConfigDto.machineNo);
    }


    public void initCountDownTimer() {
        touchTimer = new CountDownTimer((totalSecond) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvTime.setText(String.valueOf(totalSecond - (++curSecond)));
            }

            @Override
            public void onFinish() {
                stopTimer();
                showFragmentSelect();
                hideFooter();
            }
        };

        finishOrderTimer = new CountDownTimer(7 * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvTime.setText((millisUntilFinished / 1000) + "");
            }

            @Override
            public void onFinish() {
                finishOrderTimer.cancel();
                showFragmentSelect();
                hideFooter();
            }
        };
    }

    /**
     * 开始计时显示内容细节
     */
    public void startTimer() {
        if (!isTimerRunning) {
            touchTimer.start();
            isTimerRunning = true;
        }
    }

    /**
     * 停止计时显示内容
     */
    public void stopTimer() {
        if (isTimerRunning) {
            touchTimer.cancel();
            curSecond = 0;
            isTimerRunning = false;
        }
    }


    public void showFooter() {
        tvBack.setVisibility(View.VISIBLE);
        tvTime.setVisibility(View.VISIBLE);
    }

    public void hideFooter() {
        tvBack.setVisibility(View.INVISIBLE);
        tvTime.setVisibility(View.INVISIBLE);
    }

    private void initLogo() {
        try {
            File file = FileUtils.getLocalImageByName("logo.png");
            RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).signature(new ObjectKey(System.currentTimeMillis()));
            if (file.exists() && FileUtils.checkFileByName("logo.png")) {
                Glide.with(this).load(file).apply(options).into(ivLogo);
            } else {
                if (file.exists()) {
                    file.delete();
                }
                ThreadManager.getThreadPollProxy().execute(() -> {
                    String url = OssUtil.getInstance(MainA.this).getURL("images/logo/" + MachineContainer.machineConfigDto.merchantId + "/logo.png");
                    Log.i(TAG, "initLogo: 图片下载路径：" + url);
                    ImageDownloadUtil.getInstance().download(url, "/sgu6/images/", "logo.png", new ImageDownloadUtil.OnDownloadListener() {
                        @Override
                        public void onDownloadSuccess() {
                            RequestOptions ro = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).signature(new ObjectKey(System.currentTimeMillis()));
                            runOnUiThread(() -> Glide.with(MainA.this).load(url).apply(ro).into(ivLogo));
                        }

                        @Override
                        public void onDownloading(int progress) {
                            Log.i(TAG, "onDownloading: " + progress);
                        }

                        @Override
                        public void onDownloadFailed(String url) {
                            Log.i(TAG, "onDownloadFailed: ");
                            try {
                                File file = FileUtils.getLocalImageByName("logo.png");
                                file.delete();
                            } catch (Exception e) {
                                Log.i(TAG, "onDownloadFailed: " + e.getLocalizedMessage());
                            }
                        }
                    });
                });

            }
//
        } catch (Exception e) {
            Log.i(TAG, "initLogo: " + e.getLocalizedMessage());
        }
    }

    /**
     * 初始化广告视频
     * 第一次加载，则加载默认拾谷鸟的视频
     * 用户要加载自己的视频，需自己在网页上进行更新
     */
    public void initAD() {
        // FIXME: 2019-06-14 视频广告切换全屏时，倒计时需取消
        //创建缓存代理
        String videoNames = MachineContainer.machineConfigDto.videoNames;
        String[] a = videoNames.split(",");
        videoUrls.clear();
        videoUrls.addAll(Arrays.asList(a));
        proxy = new HttpProxyCacheServer.Builder(this)
                .maxCacheSize(1024 * 1024 * 1024) //1Gb 缓存
                .maxCacheFilesCount(5)//最大缓存5个视频
                .build();
        playVideo();
    }

    private void showFragmentBuy() {
        if (!buyF.isVisible()) {
            ft = fm.beginTransaction();
            ft.show(buyF);
            ft.hide(selectF);
            ft.hide(millF);
            ft.hide(waterF);
            ft.commitAllowingStateLoss();
        }
    }

    private void showFragmentSelect() {
        if (!selectF.isVisible()) {
            ft = fm.beginTransaction();
            ft.show(selectF);
            ft.hide(buyF);
            ft.hide(millF);
            ft.hide(waterF);
            ft.commitAllowingStateLoss();
        }
    }

    private void showFragmentMill() {
        if (!millF.isVisible()) {
            ft = fm.beginTransaction();
            ft.show(millF);
            ft.hide(buyF);
            ft.hide(selectF);
            ft.hide(waterF);
            ft.commitAllowingStateLoss();
        }
    }

    private void showFragmentWater() {
        if (!waterF.isVisible()) {
            ft = fm.beginTransaction();
            ft.show(waterF);
            ft.hide(buyF);
            ft.hide(selectF);
            ft.hide(millF);
            ft.commitAllowingStateLoss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelectEvent(SelectTypeEvent event) {
        showFragmentBuy();
        showFooter();
        startTimer();
    }

    /**
     * 广告更新回调
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAdvertiseEvent(AppAdDto event) {
        curAdPosition = 0;
        videoUrls.clear();
        StringBuilder urls = new StringBuilder();
        int len = event.getAds().size();
        for (int i = 0; i < len; i++) {
            String url = event.getAds().get(i);

            if (len == i + 1) {
                urls = urls.append(url);
            } else {
                urls = urls.append(url).append(",");
            }
            videoUrls.add(url);
        }
        playVideo();
        NettyHelper.postMsgWithCommandResp(MachineContainer.machineConfigDto.machineNo, "[" + MachineContainer.machineConfigDto.machineNo + "] 广告更新成功");
        MachineContainer.machineConfigDto.videoNames = urls.toString();
        try {
            machineConfig.updateMachineConfig(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWarningEvent(WarningEvent event) {
        if (event.showWarning) {
            showWarning(event.content);
        } else {
            hideWarning();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMachineStatusEvent(MachineStatusEvent event) {

        MachineContainer.setMachineStatus(event.statusCode);
        switch (event.statusCode) {
            case -1: //停机
//                showWarning("机器停机");
                break;
            case 0: //离线
                showWarning("机器离线");
//                showFragmentSelect();
                break;
            case 1: //待机
                MachineContainer.setMachineStatus(MachineStatusEnum.待机.code());
                hideWarning();
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.电量.code()));
                break;
            case 2: //工作中
                hideWarning();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataRefreshEvent(DataRefreshEvent event) {
        File file = FileUtils.getLocalImageByName("logo.png");
        if (file.exists()) {
            try {
                file.delete();
            } catch (Exception e) {
                Log.i(TAG, "onDataRefreshEvent: " + e.getLocalizedMessage());
            }
        }
        initLogo();
    }


    @SuppressLint("NewApi")
    public void showWarning(String content) {
        if (!Machine.warnInfo.toString().contains(content)) {
            Machine.warnInfo.append(" " + content);
        }
        tvMachineStatus.setText(Machine.warnInfo.toString());
        tvMachineStatus.setVisibility(View.VISIBLE);
    }

    public void hideWarning() {
        if (MachineContainer.getMachineStatus() == MachineStatusEnum.待机.code()) {
            tvMachineStatus.setVisibility(View.GONE);
            Machine.warnInfo = new StringBuilder("");
        } else {
            tvMachineStatus.setText("机器离线");
            Machine.warnInfo = new StringBuilder("机器离线");
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                if (isTimerRunning) {
                    curSecond = 0;
                    touchTimer.cancel();
                    isTimerRunning = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                if (!isTimerRunning) {
                    touchTimer.start();
                    isTimerRunning = true;
                }
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAppEvent(AppVersionDto event) {
        updateTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (MachineContainer.getMachineStatus() == MachineStatusEnum.待机.code()) {
                    updateF = new UpdateDialogF();
                    Bundle bundle = new Bundle();
                    bundle.putString("apkUrl", event.getUrl() + event.getApp());
                    updateF.setArguments(bundle);
                    updateF.setCancelable(false);
                    updateF.show(fm, "UpdateDialogFragment");

                    updateTimer.cancel();
                    updateTimer = null;
                } else {
                    Log.i(TAG, "run: " + MachineContainer.getMachineStatus());
                }
            }
        }, 1000, 10000);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMachineIdEvent(MachineIdEvent event) {
        MachineContainer.machineConfigDto.machineNo = event.machineNo;
        try {
            machineConfig.updateMachineConfig(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(Constant.FILE_ROOT_PATH + "/sgu6/images/");
        String[] files = file.list();
        for (int i = 0; i < files.length; i++) {
            File f = new File(Constant.FILE_ROOT_PATH + "/sgu6/images/" + files[i]);
            if (f.exists()) {
                try {
                    f.delete();
                } catch (Exception e) {
                    Log.i(TAG, "onMachineIdEvent: " + e.getLocalizedMessage());
                }
            }
        }

        MachineContainer.machineConfigDto.machineNo = event.machineNo;
        try {
            machineConfig.updateMachineConfig(MainA.this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        restartApp();
    }

    public void restartApp() {
        for (int i = 0; i < activities.size(); i++) {
            activities.get(i).finish();
        }
//        Intent intent = new Intent(this, MainA.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(intent);
//        try {
//            Process.killProcess(Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
//        } catch (Exception e) {
//            Log.i(TAG, "restartApp: " + e.getLocalizedMessage());
//        }

        Intent intent = getBaseContext().getPackageManager()
                .getLaunchIntentForPackage(getBaseContext().getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
        System.exit(0);
    }


    @Override
    public void onCompletion(MediaPlayer mp) {
        curAdPosition++;
        playVideo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unbindService(conn);
            stopService(locationServiceI);
            stopService(phoneSignalStateServiceI);
            EventBus.getDefault().unregister(this);
            if (touchTimer != null) {
                touchTimer.cancel();
                touchTimer = null;
            }
            heartTimer = null;
            updateTimer = null;
            powerTimer = null;
        } catch (Exception e) {
            Log.i(TAG, "onDestroy: ");
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!videoView.isPlaying()) {
            videoView.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (videoView.isPlaying()) {
            videoView.pause();
        }
    }


    public void playVideo() {
        int position = curAdPosition % videoUrls.size();
        String video_url = proxy.getProxyUrl(videoUrls.get(position));
        videoView.setVideoPath(video_url);
//        videoView.setMediaController(new MediaController(this));
        videoView.setOnCompletionListener(this);
        videoView.setOnErrorListener(this);
        videoView.setKeepScreenOn(true);
        videoView.start();
    }

    @OnClick(R.id.tv_back)
    public void onClickBack() {
        showFragmentSelect();
        hideFooter();
        stopTimer();
    }


    @OnLongClick(R.id.iv_logo)
    public boolean onLongClickLogo() {
        startActivity(new Intent(this, LoginA.class));
        return true;
    }

    @OnClick(R.id.tv_machine_no)
    public void OnMachineNo() {
        CrashReport.testJavaCrash();
    }


    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        videoView.stopPlayback(); //播放异常，则停止播放，防止弹窗使界面阻塞
        curAdPosition++;
        playVideo();
        return true;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSignalStrengthEvent(SignalStrengthsEvent event) {
        //网络类型记忆网络信号强度事件
        signalView.updateSignalStrength(event.gsmSignalStrength);
        switch (event.type) {
            case 0:
                signalView.updateNetType("WiFi");
                break;
            case 1:
                signalView.updateNetType("3G");
                break;
            case 2:
                signalView.updateNetType("4G");
                break;
            case 3:
                signalView.updateNetType("X");
                signalView.updateSignalStrength(0);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onErrorEvent(ApiErrorDto dto) {
        ToastUtil.showLongToast(this, dto.getErrMsg());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetChange(NetChangeEvent event) {
        loadMachineCache();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSysNoticeEvent(SysNoticeDto sysNoticeDto) {
        String str_machines = sysNoticeDto.getMachineNos();
        if (str_machines.contains(MachineContainer.machineConfigDto.machineNo)) {
            showWarning(sysNoticeDto.getNotice());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMakeRiceEvent(MakeRiceEvent event) {
        showFragmentMill();
        hideFooter();
        stopTimer();

        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String makeRiceCmd = String.format(MachineCmdEnum.碾米.code(), event.makeNo, MachineContainer.machineConfigDto.packageWeight);
        //发送碾米指令
        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(makeRiceCmd));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMakeWaterEvent(MakeWaterEvent event) {
        showFragmentWater();
        hideFooter();
        stopTimer();
        String makeRiceCmd;
        tvMachineNo.postDelayed(new Runnable() {
            @Override
            public void run() {
                String makeRiceCmd1 = MachineCmdEnum.关闭灯箱.code();
                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(makeRiceCmd1));
                MachineContainer.orderInfoCacheDto.setFinishNo(5);
                NettyHelper.postMsgWithFinishOrderReq(MachineContainer.orderInfoCacheDto.getBarnId(), MachineContainer.machineConfigDto.machineNo, MachineContainer.orderInfoCacheDto.getOrderNo(), MachineContainer.orderInfoCacheDto.getFinishNo(), MachineContainer.orderInfoCacheDto.getMakeNum());
                EventBus.getDefault().post(new FinishOrderEvent());
            }
        }, 105 * 1000);
        makeRiceCmd = MachineCmdEnum.打开灯箱.code();
        //发送碾米指令
        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(makeRiceCmd));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinishOrderEvent(FinishOrderEvent event) {
        showFooter();
        stopTimer();
        startFinishOrderTimer();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMachineCmdEvent(MachineCmdEvent event) {
        //远程控制发送机器指令
        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(event.cmd));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateDomainEvent(UpdateDomainEvent event) {
        if (!event.adminApiDomain.equals("null") && event.adminApiDomain.length() > 0) {
            MachineContainer.machineConfigDto.adminApiDomain = event.adminApiDomain;
        }

        if (!event.apiDomain.equals("null") && event.apiDomain.length() > 0) {
            MachineContainer.machineConfigDto.apiDomain = event.apiDomain;
        }

        if (!event.adminLoginApiDomain.equals("null") && event.adminLoginApiDomain.length() > 0) {
            MachineContainer.machineConfigDto.adminLoginApiDomain = event.adminLoginApiDomain;
        }

        if (!event.payDomain.equals("null") && event.payDomain.length() > 0) {
            MachineContainer.machineConfigDto.payDomain = event.payDomain;
        }

        if (!event.socketUrl.equals("null") && event.socketUrl.length() > 0) {
            MachineContainer.machineConfigDto.socketUrl = event.socketUrl;
        }
        if (!event.redisUrl.equals("null") && event.redisUrl.length() > 0) {
            MachineContainer.machineConfigDto.redisUrl = event.redisUrl;
        }

        try {
            machineConfig.updateMachineConfig(this);
            restartApp();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();//注释掉这行,back键不退出activity
        Process.killProcess(Process.myPid());
    }


    public double getValue(byte[] cmd) {
        byte[] v = new byte[4];
        System.arraycopy(cmd, 3, v, 0, 4);
        int value = HexUtil.byteToInt2(v);
        v = null;
        return value * 0.0001 * 100 / 100;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPowerSaveEvent(PowerSaveEvent event) {
        String day = DateUtils.getDay();
        try {
            double value = getValue(event.cmd);
            if (event.type == 1) {
                DBManager.getInstance(this).insertVoltage(new VoltageDto(value, day));
            } else if (event.type == 2) {
                DBManager.getInstance(this).insertEletric(new EletricDto(value, day));
            } else if (event.type == 3) {
                DBManager.getInstance(this).insertPower(new PowerDto(value, day));
            } else {
                DBManager.getInstance(this).insertCharge(new ChargeDto(value, day));
                ThreadManager.getThreadPollProxy().execute(new Runnable() {
                    @Override
                    public void run() {
                        machineP.postElectricity(new ElectricityParams(MachineContainer.machineConfigDto.machineNo, value));
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startPowerTimer() {
        Thread powerThread = new Thread(new Runnable() {
            @Override
            public void run() {
                powerTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try {
                            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.电压.code()));
//                            Thread.sleep(1000);
                            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.电流.code()));
//                            Thread.sleep(1000);
                            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.功率.code()));
//                            Thread.sleep(1000);
                            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.电量.code()));
                        } catch (Exception e) {
                            Log.i(TAG, "run: " + e.getLocalizedMessage());
                        }
                    }
                }, 10 * 1000, 60 * 60 * 1000);
            }
        });
        powerThread.start();


    }

}
